//package com.pansoft.openplanet.manager;
//
//import android.content.Context;
//import android.util.Log;
//
//import com.breadwallet.core.BRCoreKey;
//import com.breadwallet.core.BRCoreMasterPubKey;
//import com.breadwallet.tools.manager.BRSharedPrefs;
//import com.breadwallet.tools.security.BRKeyStore;
//import com.breadwallet.tools.security.PostAuth;
//import com.breadwallet.tools.threads.executor.BRExecutor;
//import com.breadwallet.tools.util.BRConstants;
//import com.breadwallet.tools.util.Utils;
//import com.breadwallet.wallet.WalletsMaster;
//import com.breadwallet.wallet.abstracts.BaseWalletManager;
//import com.efounder.constant.EnvironmentVariable;
//import com.pansoft.openplanet.bean.Account;
//
//import java.util.Arrays;
//
//import static com.breadwallet.core.BRCoreKey.decodeHex;
//import static com.breadwallet.core.BRCoreKey.getAuthPublicKeyForAPI;
//import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
//
///**
// * @author will
// * 调用BreadWalletLib，生成和恢复BTC账户
// */
//public class BTCWalletManager {
//
//    private Context mContext;
//
//    public BTCWalletManager(Context mContext) {
//        this.mContext = mContext;
//    }
//
//    /**
//     * 创建钱包，生成助记词，进入备份助记词界面
//     */
//    public void createWallet(final String avatar, final String name, final BTCWalletCreateListener btcWalletCreateListener) {
//
//        BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() {
//            @Override
//            public void run() {
//                WalletsMaster m = WalletsMaster.getInstance(mContext);
//                m.wipeWalletButKeystore(mContext);
//                m.wipeKeyStore(mContext);
//                //生成助记词
//                boolean success = WalletsMaster.getInstance(mContext)
//                        .generateRandomSeed(mContext);
//                if (success) {
//                    //初始化钱包
//                    WalletsMaster.getInstance(mContext).initWallets(mContext);
//
//                    //读取助记词
//
//                    WalletsMaster.getInstance(mContext).getCurrentWallet(mContext).refreshAddress(mContext);
//                    try {
//                        byte[] raw = BRKeyStore.getPhrase(mContext, BRConstants.SHOW_PHRASE_REQUEST_CODE);
//                        final String cleanPhrase = new String(raw);
//                        //保存钱包到数据库
//                        final Account account = saveWallet(avatar, name);
//                        BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (btcWalletCreateListener != null) {
//                                    if (account != null) {
//                                        btcWalletCreateListener.onCreateSuccess(cleanPhrase, account);
//                                    } else {
//                                        btcWalletCreateListener.onCreateFail();
//                                    }
//
//                                }
//                            }
//                        });
//
//                    } catch (Exception e) {
//                        BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (btcWalletCreateListener != null) {
//                                    btcWalletCreateListener.onCreateFail();
//                                }
//                            }
//                        });
//
//                        e.printStackTrace();
//                    }
//                } else {
//                    BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (btcWalletCreateListener != null) {
//                                btcWalletCreateListener.onCreateFail();
//                            }
//                        }
//                    });
//                }
//            }
//        });
//    }
//
//    /**
//     * 保存钱包到数据库
//     */
//    private Account saveWallet(String avatar, String name) {
//
//        final Account account = new Account();
//        //保存私钥
//        byte[] privKey = BRKeyStore.getAuthKey(mContext);
//        BRCoreKey brCoreKey = new BRCoreKey(privKey);
//
//        account.setSecretPrivateKey(brCoreKey.getPrivKey());
//        //保存公钥
//        account.setPublicKey(Utils.bytesToHex(new BRCoreMasterPubKey(BRKeyStore.getMasterPublicKey(mContext),false).getPubKey()));
//        //保存地址
//        WalletsMaster.getInstance(mContext).getCurrentWallet(mContext).refreshAddress(mContext);
//        final BaseWalletManager wallet = WalletsMaster.getInstance(mContext).getCurrentWallet(mContext);
//        String mReceiveAddress = BRSharedPrefs.getReceiveAddress(mContext, wallet.getIso(mContext));
//        String decorated = wallet.decorateAddress(mContext, mReceiveAddress);
//        account.setAddress(decorated);
//
//        account.setAccountAvatar(avatar);
//        account.setAcccountName(name);
//        account.setBlockChainName(IPAssetsConstant.ChainEnum.BTC.chainName);
////                                        account.setFileName();
//        account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
//        account.setMaster(false);
////        account.setCurrentShow(true);
////                                        account.setMainAccoutAddress();
//        account.setEnable(false);
//        return account;
//
//    }
//
//
//    /**
//     * 恢复钱包
//     * @param mnemonic 助记词
//     * @param avatar 头像
//     * @param name 钱包名
//     */
//    public void restoreWalletbyMnemonic(final String mnemonic, final String avatar, final String name,
//                              final BTCWalletRestoreListener btcWalletRestoreListener) {
//        BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() {
//            @Override
//            public void run() {
////                WalletsMaster m = WalletsMaster.getInstance(mContext);
////                BaseWalletManager wm = m.getWalletByIso(mContext, "BTC");
////                wm.wipeData(mContext);
////                m.wipeKeyStore(mContext);
//                PostAuth.getInstance().setPhraseForKeyStore(mnemonic);
//                BRSharedPrefs.putAllowSpend(mContext, BRSharedPrefs.getCurrentWalletIso(mContext), false);
//                if (Utils.isNullOrEmpty(mnemonic)) {
//                    Log.e("RESTORE_BTC", "onRecoverWalletAuth: phraseForKeyStore is null or empty");
//                    BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (btcWalletRestoreListener != null) {
//                                btcWalletRestoreListener.onRestoreFail();
//                            }
//                        }
//                    });
//
//                    return;
//                }
//                byte[] bytePhrase = new byte[0];
//
//                try {
//                    boolean success = false;
//                    try {
//                        success = BRKeyStore.putPhrase(mnemonic.getBytes(),
//                                mContext, BRConstants.PUT_PHRASE_RECOVERY_WALLET_REQUEST_CODE);
//                    } catch (Exception e) {
//                        BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (btcWalletRestoreListener != null) {
//                                    btcWalletRestoreListener.onRestoreFail();
//                                }
//                            }
//                        });
//                        e.printStackTrace();
//                    }
//
//                    if (!success) {
//                        BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (btcWalletRestoreListener != null) {
//                                    btcWalletRestoreListener.onRestoreFail();
//                                }
//                            }
//                        });
//                        Log.e("RESTORE_BTC", "onRecoverWalletAuth, !success && authAsked");
//                    } else {
//                        if (mnemonic.length() != 0) {
//                            final Account account = new Account();
//                            BRSharedPrefs.putPhraseWroteDown(mContext, true);
//                            //助记词生成seed
//                            byte[] seed = BRCoreKey.getSeedFromPhrase(mnemonic.getBytes());
//                            //seed得到authKey
//                            byte[] authKey = BRCoreKey.getAuthPrivKeyForAPI(seed);
//                            //authKey得到BRCoreKey
//
//                            //BRCoreKey得到私钥
//
//                            //存到KeyStore
//                            BRKeyStore.putAuthKey(authKey, mContext);
//
//                            //由助记词得到MasterPubKey
//                            final BRCoreMasterPubKey mpk = new BRCoreMasterPubKey(mnemonic.getBytes(), true);
//
//
//                            BRCoreKey brCoreKey1 = mpk.getPubKeyAsCoreKey();
//                            byte[] pub = brCoreKey1.getPubKey();
//                            String pubkey1 = Utils.bytesToHex(pub);
//                            BRCoreKey brCoreKey = new BRCoreKey(seed, 0, 0);
//                            String prikey2 = brCoreKey.getPrivKey();
//                            String addr = brCoreKey.address();
//                            //保存公钥
//                            account.setPublicKey(Utils.bytesToHex(mpk.getPubKey()));
//                            //存到KeyStore
//                            BRKeyStore.putMasterPublicKey(mpk.serialize(), mContext);
//                            final BaseWalletManager wallet = WalletsMaster.getInstance(mContext).getCurrentWallet(mContext);
//                            wallet.refreshAddress(mContext);
//
//                            String mReceiveAddress = BRSharedPrefs.getReceiveAddress(mContext, wallet.getIso(mContext));
//                            String decorated = wallet.decorateAddress(mContext, mReceiveAddress);
//                            account.setAddress(decorated);
//                            account.setAccountAvatar(avatar);
//                            account.setAcccountName(name);
//                            account.setBlockChainName(IPAssetsConstant.ChainEnum.BTC.chainName);
////                                        account.setFileName();
//                            account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
//
//                            account.setMaster(false);
////                            account.setCurrentShow(true);
////                                        account.setMainAccoutAddress();
//                            account.setEnable(false);
//                            BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (btcWalletRestoreListener != null) {
//                                        btcWalletRestoreListener.onRestoreSuccess(account);
//                                    }
//                                }
//                            });
//
//                        }
//
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (btcWalletRestoreListener != null) {
//                                btcWalletRestoreListener.onRestoreFail();
//                            }
//                        }
//                    });
//                } finally {
//                    Arrays.fill(bytePhrase, (byte) 0);
//                }
//            }
//        });
//
//    }
//
//
//    public  void restoreWalletByPrivKey(final String privKey, final String avatar, final String name,
//                                       final BTCWalletRestoreListener btcWalletRestoreListener) {
//        BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() {
//            @Override
//            public void run() {
//                byte[] authKey = privKey.getBytes();
//                BRCoreKey brCoreKey = new BRCoreKey(authKey);
//                final Account account = new Account();
//                account.setSecretPrivateKey(brCoreKey.getPrivKey());
//
//                BRKeyStore.putAuthKey(authKey, mContext);
//                String pubKey = getAuthPublicKeyForAPI(authKey);
//                final BRCoreMasterPubKey mpk = new BRCoreMasterPubKey(decodeHex(pubKey), false);
//                BRKeyStore.putMasterPublicKey(mpk.serialize(), mContext);
//
//                WalletsMaster.getInstance(mContext).getCurrentWallet(mContext).refreshAddress(mContext);
//                final BaseWalletManager wallet = WalletsMaster.getInstance(mContext).getCurrentWallet(mContext);
//                String mReceiveAddress = BRSharedPrefs.getReceiveAddress(mContext, wallet.getIso(mContext));
//                String decorated = wallet.decorateAddress(mContext, mReceiveAddress);
//                account.setAddress(decorated);
//                account.setAccountAvatar(avatar);
//                account.setAcccountName(name);
//                account.setBlockChainName(IPAssetsConstant.ChainEnum.BTC.chainName);
////                                        account.setFileName();
//                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
//                //保存公钥
//                account.setPublicKey(Utils.bytesToHex(mpk.getPubKey()));
//                account.setMaster(false);
////                            account.setCurrentShow(true);
////                                        account.setMainAccoutAddress();
//                account.setEnable(false);
//                BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (btcWalletRestoreListener != null) {
//                            btcWalletRestoreListener.onRestoreSuccess(account);
//                        }
//                    }
//                });
//            }
//        });
//    }
//
//
//    public interface BTCWalletCreateListener{
//        void onCreateSuccess(String mnemonic, Account account);
//
//        void onCreateFail();
//    }
//
//    public interface BTCWalletRestoreListener{
//        void onRestoreSuccess(Account account);
//
//        void onRestoreFail();
//    }
//}
